<template lang="html">
  <div v-loading="loading" class="coupon-panel">
    <el-button type="primary" @click="couponDialog('post')">添加</el-button>
    <el-dialog
      ref="fafangDiaRef"
      v-loading="loading"
      title="发放优惠券"
      :visible.sync="adminGiveDiaIsShow"
      class="diaForm"
      :append-to-body="false">
      <el-form
        ref="adminGiveRef"
        :model="adminGiveForm"
        :rules="adminGiveRules"
        label-width="170px"
      >
        <el-form-item label="优惠券名称" prop="coupon_name">
          <el-col :span="15">
            <el-input
              v-model="adminGiveForm.coupon_name"
              type="text"
              disabled
              placeholder="请输入优惠券名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="发放对象" prop="coupon_object_type">
          <el-col :span="15">
            <el-radio v-model="adminGiveForm.coupon_object_type" label="1">全部会员</el-radio>
            <el-radio v-model="adminGiveForm.coupon_object_type" label="2">全部会员(没下单会员)</el-radio>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="adminGiveCoupon()"
          >确认
          </el-button>
          <el-button @click="adminGiveDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      ref="selectProductDiaRef"
      v-loading="loading"
      title="适用商品"
      :visible.sync="selectProductDiaIsShow"
      class="diaForm"
      :append-to-body="false">
      <el-table
        ref="productTableDataRef"
        :data="productTableData"
        border
        style="width: 100%"
        @selection-change="selectionProductChange"
      >
        <el-table-column
          type="selection"
          prop="id"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="商品名称"
        />
        <el-table-column
          label="主图"
          width="100"
        >
          <template slot-scope="scope">
            <img :src="scope.row.logo_url" alt="" style="height: 50px;width: 50px;">
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="selectProductConfirm">确认</el-button>
      <el-button type="danger" @click="selectProductDiaIsShow = false">取消</el-button>
    </el-dialog>
    <el-dialog v-loading="loading" title="编辑" :visible.sync="couponDiaIsShow" class="diaForm" :append-to-body="false">
      <el-form
        ref="couponRef"
        :model="couponForm"
        :rules="couponRules"
        label-width="170px"
      >
        <el-form-item label="优惠券名称" prop="coupon_name">
          <el-col :span="15">
            <el-input
              v-model="couponForm.coupon_name"
              type="text"
              placeholder="请输入优惠券名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="使用条件" prop="coupon_use_min_price">
          <el-col :span="15">
            <el-input
              v-model="couponForm.coupon_use_min_price"
              type="text"
              placeholder="请输入最低消费多少金额可用优惠券"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="兑换优惠券消耗的积分" prop="coupon_exchange_integral">
          <el-col :span="15">
            <el-input
              v-model="couponForm.coupon_exchange_integral"
              type="text"
              placeholder="请输入兑换优惠券消耗的积分"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="coupon_type">
          <el-col :span="15">
            <el-radio v-for="item in coupon_typeAttr" v-model="couponForm.coupon_type" :label="item.key">
              {{item.value}}
            </el-radio>
          </el-col>
        </el-form-item>
        <!--        1 满减-->
        <el-form-item v-if="couponForm.coupon_type === 1" label="满减属性" prop="coupon_type">
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_use_min_price"
              type="number"
              :min="0"
              :max="10000"
              placeholder="满"
              disabled
            />
          </el-col>
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_type_jian_price"
              type="number"
              :min="0"
              :max="10000"
              placeholder="减"
            />
          </el-col>
        </el-form-item>
        <!--        2 折扣-->
        <el-form-item v-if="couponForm.coupon_type === 2" label="折扣属性" prop="coupon_type_discount_price">
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_type_discount_price"
              type="number"
              :min="1"
              :max="99"
              placeholder="折扣"
            />
          </el-col>
          <el-col :span="12" class="desc">
            0
            <折扣
            <100，例如99，就是99折
          </el-col>
        </el-form-item>
        <!--        3 随机减金额-->
        <el-form-item v-if="couponForm.coupon_type === 3" label="随机减金额属性" prop="coupon_type_random_min_price">
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_type_random_min_price"
              type="number"
              :min="0"
              :max="10000"
              placeholder="随机最小值"
            />
          </el-col>
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_type_random_max_price"
              type="number"
              :min="0"
              :max="10000"
              placeholder="随机最大值"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="适用商品" prop="coupon_type_discount_price">
          <el-col :span="6">
            <el-switch
              v-model="couponForm.coupon_all_product"
              active-text="全部商品"
              inactive-text="部分商品">
            </el-switch>
          </el-col>
          <el-col v-if="couponForm.coupon_all_product === false" :span="18">
            <el-button type="primary" @click="selectProductDiaIsShow = true">选择商品</el-button>
          </el-col>
          <el-col v-if="couponForm.coupon_all_product === false" v-for="item in couponForm.select_products" :span="6">
            <div><img :src="item.logo_url" alt="" style="height: 150px;width: 150px;"></div>
            <div style="font-size: 10px;">{{item.name}}</div>
          </el-col>
        </el-form-item>
        <el-form-item label="生效时长，按秒计" prop="coupon_valid_time">
          <el-col :span="6">
            <el-input-number
              v-model="couponForm.coupon_valid_time"
              type="number"
              :min="1"
              :max="8000000"
              placeholder="生效时长"
            />
          </el-col>
          <el-col :span="12" class="desc">
            86400就是一天，7天就是 7*86400=604800
          </el-col>
        </el-form-item>
        <el-form-item label="首页领取设置">
          <el-col :span="6">
            <el-switch
              v-model="couponForm.coupon_issue_status"
              active-text="开启"
              inactive-text="关闭">
            </el-switch>
          </el-col>
          <el-col v-if="couponForm.coupon_issue_status === true" :span="6">
            <el-date-picker
              v-model="couponForm.coupon_issue_time"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="issueTimestampPickerOptions"
              range-separator="至"
              start-placeholder="领取开始时间"
              end-placeholder="领取结束时间"
            />
          </el-col>
          <br>
          <el-col v-if="couponForm.coupon_issue_status === true" :span="5">
            发放总量：
          </el-col>
          <el-col v-if="couponForm.coupon_issue_status === true" :span="6">
            <el-input-number
              v-model="couponForm.coupon_issue_total_count"
              type="number"
              style="width: 300px"
              :min="0"
              :max="1000000"
              placeholder="发放总量,0不限制"
            />
          </el-col>
          <el-col :span="24">
            <el-col v-if="couponForm.coupon_issue_status === true" :span="5">
              单人最多领取数量：
            </el-col>
            <el-col v-if="couponForm.coupon_issue_status === true" :span="6">
              <el-input-number
                v-model="couponForm.coupon_issue_single_limit"
                type="number"
                style="width: 300px"
                :min="0"
                :max="1000000"
                placeholder="单人最多领取数量,0不限制"
              />
            </el-col>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editCoupon()"
          >确认
          </el-button>
          <el-button @click="couponDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="couponTableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="优惠券名称"
      />
      <el-table-column
        prop="exchange_integral"
        label="兑换消耗的积分值"
      />
      <el-table-column
        label="优惠券类型"
      >
        <template slot-scope="scope">
          {{scope.row.extend_desc}}
          <!--          <div v-if=" === 1">-->
          <!--            满{{scope.row.use_min_price}}减{{scope.row.type_jian_price}}-->
          <!--          </div>-->
          <!--          <div v-if="scope.row.type === 2">-->
          <!--            满{{scope.row.use_min_price}}折扣{{scope.row.discount_price}}-->
          <!--          </div>-->
          <!--          <div v-if="scope.row.type === 3">-->
          <!--            满{{scope.row.use_min_price}}优惠随机金额：{{scope.row.random_min_price
          }} ~ {{scope.row.random_max_price}}-->
          <!--          </div>-->
        </template>
      </el-table-column>
      <el-table-column
        label="首页领取详情"
        width="360"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.issue_status === true">
            <div>
              发放总量:{{scope.row.issue_total_count === 0 ? '不限制' : scope.row.issue_total_count }}
            </div>
            <div>
              单人领取数量:{{scope.row.issue_single_limit === 0 ? '不限制' : scope.row.issue_single_limit }}
            </div>
            <div>
              发放时间:{{scope.row.issue_start_time}} ~ {{scope.row.issue_end_time}}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="coupon_product_ids"
        label="使用的商品id，如果为null则是全部都使用"
      />
      <el-table-column
        prop="create_time"
        label="创建时间"
      />
      <el-table-column
        prop="update_time"
        label="更新时间"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="couponDialog('put',scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="couponDialog('admin_give',scope.row)">发放优惠券</el-button>
          <el-button type="text" size="small" @click="deleteCoupon(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px">
      <el-pagination
        :current-page="couponTableDataPaginateCurrentPage"
        :page-sizes="couponTableDataPaginateTotalPageSizes"
        :page-size="couponTableDataPaginateTotalPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="couponTableDataPaginateTotal"
        @size-change="couponTableDataHandleSizeChange"
        @current-change="couponTableDataHandleCurrentChange"
      >
        <!-- <span>当前{{ couponTableDataPaginateCurrentPage }}页，</span>
                        <span>共{{ couponTableDataPaginateLastPage }}页</span> -->
      </el-pagination>
    </div>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  data() {
    return {
      loading: false,
      couponSearchForm: {},
      couponTableData: [],
      coupon_typeAttr: [
        { key: 1, value: '满减' },
        { key: 2, value: '折扣' },
        { key: 3, value: '随机减金额' }
      ],
      couponTableDataPaginateCurrentPage: 1,
      couponTableDataPaginateTotal: 1,
      couponTableDataPaginateLastPage: 1,
      couponTableDataPaginateTotalPageSize: 10,
      couponTableDataPaginateTotalPageSizes: [10, 20, 50, 100],
      couponTab: [],
      couponEditType: 'post',
      couponDiaIsShow: false,
      selectProductDiaIsShow: false,
      productTableData: [],
      selectProducts: [],
      adminGiveForm: {},
      adminGiveDiaIsShow: false,
      adminGiveRules: {
        coupon_object_type: [{
          required: true,
          trigger: 'blur'
        }]
      },
      couponForm: {
        coupon_valid_time: 86400,
        select_products: [],
        coupon_product_ids: [],
        coupon_all_product: false,
        coupon_issue_status: false
      },
      issueTimestampPickerOptions: {
        shortcuts: [{
          text: '一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      coupon_type: [],
      couponRules: {
        coupon_name: [{
          required: true,
          trigger: 'blur'
        }],
        coupon_use_min_price: [{
          required: true,
          trigger: 'blur'
        }],
        coupon_exchange_integral: [{
          required: true,
          trigger: 'blur'
        }],
        coupon_type: [{
          required: true,
          trigger: 'blur'
        }],
        coupon_valid_time: [{
          required: true,
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getProductList()
    this.getCouponList()
  },
  methods: {
    selectProductConfirm() {
      this.couponForm.select_products = this.selectProducts
      this.selectProductDiaIsShow = false
    },
    selectionProductChange(val) {
      this.selectProducts = val
      console.log(val)
    },
    selectCouponType(val) {
      // 改变每页显示的条数
      this.coupon_type = val
    },
    couponTableDataHandleSizeChange(val) {
      // 改变每页显示的条数
      this.couponTableDataPaginateTotalPageSize = val
      this.getCouponList(1, this.couponTableDataPaginateTotalPageSize)
    },
    couponTableDataHandleCurrentChange(val) {
      this.couponTableDataPaginateCurrentPage = val
      this.getCouponList(val, this.couponTableDataPaginateTotalPageSize)
    },
    getCouponList(page = 1, limit = 10) {
      this.loading = true
      this.couponSearchForm.page = page
      this.couponSearchForm.limit = limit
      this.$store.dispatch('coupon/getCouponList', this.couponSearchForm).then((res) => {
        this.couponTableData = res.data.data
        this.couponTableDataPaginateTotal = res.data.total
        this.couponTableDataPaginateCurrentPage = res.data.current_page
        this.couponTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getProductList() {
      this.loading = true
      this.$store.dispatch('coupon/getProductList').then((res) => {
        this.productTableData = res.data
        this.selectProductDiaIsShow = true
        console.log(this.$refs)
        // this.selectProductDiaIsShow = true
        // // eslint-disable-next-line no-unused-vars
        // var that = this
        // setTimeout(function(that) {
        //   that.selectProductDiaIsShow = false
        // }, 0)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    deleteCoupon(row) {
      // console.log(row)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          this.$store.dispatch('coupon/deleteCoupon', { coupon_id: row.id }).then((res) => {
            this.getCouponList()
            this.loading = false
            this.couponDiaIsShow = false
            this.couponForm.select_products = []
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editCoupon() {
      switch (this.couponEditType) {
        case 'post':
          this.$refs['couponRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              switch (this.couponForm.coupon_type) {
                case 1:
                  if (this.couponForm.coupon_type_jian_price === undefined || this.couponForm.coupon_type_jian_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入满减的减值'
                    })
                    this.loading = false
                    return
                  }
                  break
                case 2:
                  if (this.couponForm.coupon_type_discount_price === undefined || this.couponForm.coupon_type_discount_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入折扣值'
                    })
                    this.loading = false
                    return
                  }
                  break
                case 3:
                  if (this.couponForm.coupon_type_random_min_price === undefined || this.couponForm.coupon_type_random_min_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入随机减最小值'
                    })
                    this.loading = false
                    return
                  }
                  if (this.couponForm.coupon_type_random_max_price === undefined || this.couponForm.coupon_type_random_max_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入随机减最大值'
                    })
                    this.loading = false
                    return
                  }
                  break
              }
              if (!this.couponForm.coupon_all_product) {
                if (this.couponForm.select_products.length === 0) {
                  this.$message({
                    type: 'error',
                    message: '至少选择一个商品'
                  })
                  this.loading = false
                  return
                }
                for (let i = 0; i < this.couponForm.select_products.length; i++) {
                  console.log(this.couponForm.coupon_product_ids.push(this.couponForm.select_products[i].id))
                  this.couponForm.coupon_product_ids.push(this.couponForm.select_products[i].id)
                }
                this.couponForm.coupon_product_ids = Array.from(new Set(this.couponForm.coupon_product_ids))
              }
              // this.couponForm.coupon_type = this.coupon_type
              this.$store.dispatch('coupon/postCoupon', this.couponForm).then((res) => {
                this.getCouponList()
                this.couponForm = {}
                this.loading = false
                this.couponDiaIsShow = false
                this.couponForm.select_products = []
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'put':
          this.$refs['couponRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              switch (this.couponForm.coupon_type) {
                case 1:
                  if (this.couponForm.coupon_type_jian_price === undefined || this.couponForm.coupon_type_jian_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入满减的减值'
                    })
                    this.loading = false
                    return
                  }
                  break
                case 2:
                  if (this.couponForm.coupon_type_discount_price === undefined || this.couponForm.coupon_type_discount_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入折扣值'
                    })
                    this.loading = false
                    return
                  }
                  break
                case 3:
                  if (this.couponForm.coupon_type_random_min_price === undefined || this.couponForm.coupon_type_random_min_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入随机减最小值'
                    })
                    this.loading = false
                    return
                  }
                  if (this.couponForm.coupon_type_random_max_price === undefined || this.couponForm.coupon_type_random_max_price === null) {
                    this.$message({
                      type: 'error',
                      message: '请输入随机减最大值'
                    })
                    this.loading = false
                    return
                  }
                  break
              }
              if (!this.couponForm.coupon_all_product) {
                if (this.couponForm.select_products.length === 0) {
                  this.$message({
                    type: 'error',
                    message: '至少选择一个商品'
                  })
                  this.loading = false
                  return
                }
                for (let i = 0; i < this.couponForm.select_products.length; i++) {
                  console.log(this.couponForm.coupon_product_ids.push(this.couponForm.select_products[i].id))
                  this.couponForm.coupon_product_ids.push(this.couponForm.select_products[i].id)
                }
                this.couponForm.coupon_product_ids = Array.from(new Set(this.couponForm.coupon_product_ids))
              }
              // this.couponForm.coupon_type = this.coupon_type
              this.$store.dispatch('coupon/putCoupon', this.couponForm).then((res) => {
                this.getCouponList()
                this.loading = false
                this.couponDiaIsShow = false
                this.couponForm.select_products = []
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
      }
    },
    adminGiveCoupon() {
      this.$refs['adminGiveRef'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('coupon/postCouponAdminGiveList', this.adminGiveForm).then((res) => {
            this.getCouponList()
            this.adminGiveForm = {}
            this.loading = false
            this.adminGiveDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    couponDialog(type, row) {
      switch (type) {
        case 'admin_give':
          this.adminGiveForm.coupon_id = row.id
          this.adminGiveForm.coupon_name = row.name
          this.adminGiveDiaIsShow = true
          break
        case 'post':
          this.couponDiaIsShow = true
          this.couponEditType = 'post'
          break
        case 'put':
          this.couponDiaIsShow = true
          this.couponEditType = 'put'
          // 这里一定要使用nextTick的方式赋值，不然会卡住input
          this.$nextTick(() => {
            var selectProducts = []
            console.log(this.$refs)
            // if (this.$refs.productTableDataRef) {
            //   this.$refs.productTableDataRef.clearSelection()
            // }
            for (let i = 0; i < this.productTableData.length; i++) {
              for (let j = 0; j < row.productsInfo.length; j++) {
                if (this.productTableData[i].id === row.productsInfo[j].id) {
                  this.$refs.productTableDataRef.toggleRowSelection(this.productTableData[i], true) // 回显
                  selectProducts.push(this.productTableData[i])
                }
              }
            }
            this.selectionProductChange(selectProducts)
            this.selectProductConfirm()

            this.$set(this.couponForm, 'coupon_id', row.id)
            this.$set(this.couponForm, 'coupon_name', row.name)
            this.$set(this.couponForm, 'coupon_exchange_integral', row.exchange_integral)
            this.$set(this.couponForm, 'coupon_use_min_price', row.use_min_price)
            this.$set(this.couponForm, 'coupon_type_jian_price', row.type_jian_price)
            this.$set(this.couponForm, 'coupon_type_discount_price', row.type_discount_price)
            this.$set(this.couponForm, 'coupon_type_random_min_price', row.type_random_min_price)
            this.$set(this.couponForm, 'coupon_type_random_max_price', row.type_random_max_price)
            this.$set(this.couponForm, 'coupon_valid_time', row.valid_time)
            this.$set(this.couponForm, 'coupon_type', row.type)
            this.$set(this.couponForm, 'coupon_all_product', row.all_product)
            this.$set(this.couponForm, 'coupon_issue_status', row.issue_status)
            this.$set(this.couponForm, 'coupon_issue_total_count', row.issue_total_count)
            this.$set(this.couponForm, 'coupon_issue_single_limit', row.issue_single_limit)
            this.$set(this.couponForm, 'coupon_issue_time', [row.issue_start_time, row.issue_end_time])
          })
          break
        default:
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.coupon-panel {
  padding: 18px;
  font-size: 10px;
}
</style>
